# Create your views here.
from django.template import Context, loader
from linktracker.models import Link
from django.shortcuts import render_to_response
from django.core.paginator import ObjectPaginator, InvalidPage

def edit(request, key):
    link=Link.objects.get(key)
    return render_to_response('links/form.html',{'action':'update/'+key, 'button':'Update'})

def update(request, key):
    link=Link.objects.get(key)
    link.link_description=request.POST['link_description']
    link.link_url=request.POST['link_url']
    link.save()
    return list(request,message="Link updated!")

def delete(request,key):
    link=Link.objects.get(key)
    link.delete()
    return list(request,message="Link deleted!")

def add(request):
    link_description=request.POST["link_description"]
    link_url=request.POST["link_url"]
    link = Link(link_description=request.POST["link_description"], link_url=request.POST["link_url"])
    link.save()
    return list(request,message='Link added!')

def new(request):
    return render_to_response('links/form.html', {'action':'add', 'button':'Add'})

def list(request, page=0, message=''):
    page =int(page)
    link_list=ObjectPaginator(Link.objects.all(), 5)
    has_previous=link_list.has_previous_page(page)
    has_next=link_list.has_next_page(page)
    dict = {'link_list' : link_list.get_page(page),
            'has_previous': has_previous,
            'previous_page': page-1,
            'has_next':has_next,
            'next_page':page+1,
            'message':message,
    }
    return render_to_response('links/list.html', dict)